
const fs = require('fs');
const readline = require('readline');
const os = require('os');
const path = require('path');

function toCamelCase(str){
  let arr = str.split(/-|_/g);
  let str2 = ''
  arr.forEach((item, index) => {
      if (index !== 0) {
          let a = item.charAt(0)
          item = item.replace(a, a.toUpperCase())
      }
      str2 = str2.concat(item)
  })
  return str2
}

// 获取所有的规则配置格式化处理
function readFile() {
  const fReadName = 'ESLint 标准配置属性.txt'
  const fRead = fs.createReadStream(fReadName);
  var objReadline = readline.createInterface({
    input: fRead
  })

  var index = 1;
  // 将要追加的规则集合
  var rules = []

  objReadline.on('line', (line)=>{
    // 过滤掉空行
    if (line.replace(/\s*/g, '') !== '') {
      if (index >= 38) {
        line = line.replace(/\s*/g, '').replace(/\:/g, ': ').replace(/\,/g, ', ').replace(/\/\//g, '// ');   
        rules.push('        ' + line)
      }
      index++;
    }
  });
  
  objReadline.on('close', ()=>{
    console.log('规则已读取成功');

    // 将具体规则追加到配置文件
    let data = fs.readFileSync("./.eslintrc.js", 'utf8').split(/\r\n|\n|\r/gm);
    data.splice(data.length - 2, 0, ...rules)
    fs.writeFile("./.eslintrc.js", data.join('\r\n'), (err) => {
      if(!err) {
        console.log('规则已全部写入.eslintrc.js文件中, 正在创建相关的规则示例文件...');

        for(let i = 0; i < rules.length; i++) {
          let tempName = rules[i].replace(/(^\s*)/g, '').split(":")[0].replace(/\"/g, '')
          tempName = toCamelCase(tempName)
          let remark = '// ' + rules[i].split("// ")[1]
          let fileName = "./example/chapter1/" + tempName + '.js'
          fs.appendFile(fileName, remark , (err) => {
            if (!err) {
              console.log('示例文件' + fileName + '创建成功')
            } else {
              console.log('示例文件' + fileName + '创建失败!!!')
            }
          })
        }

      }
    })
  });
}

readFile()